/*
**    Copyright (C) 2003-2011 Institute for Systems Biology
**                            Seattle, Washington, USA.
**
**    This library is free software; you can redistribute it and/or
**    modify it under the terms of the GNU Lesser General Public
**    License as published by the Free Software Foundation; either
**    version 3 of the License, or (at your option) any later version.
**
**    This library is distributed in the hope that it will be useful,
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**    Lesser General Public License for more details.
**
**    You should have received a copy of the GNU Lesser General Public
**    License along with this library; if not, write to the Free Software
**    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*/

package org.systemsbiology.iteration;

import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class RandomDrawIterable<T> implements Iterable<T> {

	private List<T> source;
	private long quantity;
	private Random rand;
	
	
	public RandomDrawIterable(List<T> source, long quantity, Random rand) {
		if(source == null){
			throw new IllegalArgumentException("Source must not be null");
		}
		if(quantity < 0){
			throw new IllegalArgumentException("Quantity must be positive");
		}
		this.source = source;
		this.quantity = quantity;
		this.rand = rand; //null permitted
	}

	@Override
	public Iterator<T> iterator() {
		return new RandomDrawIterator<T>(rand, source, quantity);
	}
	
	private static class RandomDrawIterator<T> implements Iterator<T>{

		private Random rand;
		private List<T> data;
		private long remainingCount;
		
		public RandomDrawIterator(Random rand, List<T> data, long remainingCount) {
			this.rand = rand;
			this.data = data;
			this.remainingCount = remainingCount;
			if(this.data.isEmpty()){
				remainingCount = 0;
			}
			if(rand == null){
				this.rand = new Random();
			}
		}

		@Override
		public boolean hasNext() {
			return remainingCount > 0;
		}

		@Override
		public T next() {
			if(remainingCount <= 0) return null;
			--remainingCount;
			return data.get(rand.nextInt(data.size()));
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException("This iterator won't do remove.");
		}
		
	}

}
